package com.aiti.lulian.workflow;

import com.aiti.lulian.mapper.TaskHistoryMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class TaskHistoryService {

    @Autowired
    private TaskHistoryMapper taskHistoryMapper;

    public List<TaskHistory> findByProcessInstanceId(String processInstanceId) {
        return taskHistoryMapper.findByProcessInstanceIdOrderByActionTimeAsc(processInstanceId);
    }

    public List<TaskHistory> findByTaskInstanceId(String taskInstanceId) {
        return taskHistoryMapper.findByTaskInstanceId(taskInstanceId);
    }

    @Transactional
    public TaskHistory recordTaskHistory(String processInstanceId, String taskDefinitionId,
                                         String taskInstanceId, ActionType action,
                                         String actor, String comment, Map<String, Object> variables) {
        TaskHistory history = new TaskHistory();
        history.setProcessInstanceId(processInstanceId);
        history.setTaskDefinitionId(taskDefinitionId);
        history.setTaskInstanceId(taskInstanceId);
        history.setAction(action);
        history.setActor(actor);
        history.setComment(comment);

        if (variables != null) {
            history.setVariables(variables);
        }

        taskHistoryMapper.insert(history);
        return history;
    }

    @Transactional
    public TaskHistory recordRejectHistory(String processInstanceId, String taskDefinitionId,
                                           String taskInstanceId, String actor,
                                           String comment, String rejectToNodeId,
                                           Map<String, Object> variables) {
        TaskHistory history = new TaskHistory();
        history.setProcessInstanceId(processInstanceId);
        history.setTaskDefinitionId(taskDefinitionId);
        history.setTaskInstanceId(taskInstanceId);
        history.setAction(ActionType.REJECT);
        history.setActor(actor);
        history.setComment(comment);
        history.setRejectToNodeId(rejectToNodeId);

        if (variables != null) {
            history.setVariables(variables);
        }
        taskHistoryMapper.insert(history);
        return history;
    }
}